package com.rbcs.budget.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.base.model.Project;
import com.rbcs.budget.model.Budget;
import com.rbcs.budget.model.BudgetItem;
import com.rbcs.budget.model.BudgetItemMonth;
import com.systop.common.modules.dept.model.Dept;
import com.systop.core.ApplicationException;
import com.systop.core.service.BaseGenericsManager;

@Service
public class BudgetManager extends BaseGenericsManager<Budget> {

	@Autowired
	private BudgetItemtManager budgetItemtManager;

	@Transactional
	public void save(Budget budget) {
		if (getDao().exists(budget, "dept", "year")) {
			throw new ApplicationException("已经存在" + budget.getYear() + "年度预算");
		}
		if (getDao().exists(budget, "singleNo")) {
			throw new ApplicationException("预算编号已存在:" + budget.getSingleNo());
		}
		getDao().saveOrUpdate(budget);
	}

	/**
	 * 删除预算，级联删除其他相关数据
	 */
	@Transactional
	public void remove(Budget budget) {
		for (BudgetItem bitem : budget.getBudgetItems()) {
			for (BudgetItemMonth bim : bitem.getBims()) {
				getDao().delete(bim);
			}
			budgetItemtManager.remove(bitem);
		}
		super.remove(budget);
	}

	/**
	 * 合计年度预算的所有科目
	 * 
	 * @param budget
	 */
	public void countYearBudget(Budget budget) {
		Double amount = 0.0;
		for (BudgetItem bi : budget.getBudgetItems()) {
			// 先合计科目的月度额
			budgetItemtManager.countItemBudget(bi);
			amount = amount + bi.getAmount();
		}
		budget.setAmount(amount);
		save(budget);
	}

	/**
	 * 判断项目是否有预算
	 * 
	 * @param p
	 * @return
	 */
	public boolean hasBudget(Project p) {
		String hql = "select count(b.id) from Budget b where b.project.id = ?";
		return ((Long) getDao().findObject(hql, p.getId()) > 0);
	}

	/**
	 * 判断部门是否有本年度预算
	 * 
	 * @param dept
	 * @param year
	 * @return
	 */
	public boolean hasBudget(Dept dept, Integer year) {
		String hql = "select count(b.id) from Budget b where b.dept.id = ? and b.year = ?  and b.project is null";
		Object[] args = new Object[] { dept.getId(), year };
		return ((Long) getDao().findObject(hql, args) > 0);
	}
}
